﻿var member_Id = $.cookie('username');


//$(function () {
//    var qsParm = new Array();
//    var query = window.location.search.substring(1);
//    var parms = query.split('&');
//    for(var i = 0; i < parms.length; i++) {
//        var pos = parms[i].indexOf('=');
//        if(pos > 0) {
//            var key = parms[i].substring(0, pos);
//            var val = parms[i].substring(pos + 1);
//            qsParm[key] = val;
//            member_Id = val;
//        }
//    }
//});

$(function () {
    var tabs = $("#tabs").tabs();
    $("#menu").menu();
});



$(function () {
    $("#accordion").accordion({
        collapsible: true,
        heightStyle: "fill"
    });

    $("#accordion-resizer").resizable({
        minHeight: 335,
        maxHeight: 335,
        resize: function () {
            $("#accordion").accordion("refresh");
        }
    });
});

var imgCount = 0;

$(function () {
    //alert(member_Id);
    var tabs = $("#tabs").tabs();
    var label;
    var idContact; //lưu để xác định nick đó đã dc add tab chưa
    var tabArray = []; //lưu để xác định nick đó đã dc add tab chưa
    var tabCounter = 1;
    var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>";
    $.getJSON("http://localhost:64395/api/Member/Get/" + member_Id, null, function (data) {
        //alert(JSON.stringify(data));
        var menuId, friendId, memberId, friendName;
        
        $.each(data, function(key, value) {
            // alert(value);
            if(key == "Name") {
                $("#contact-list-container-user-information-name").append("<b id='"+ memberId +"'>" + value + "</b>");
            }
            
            if (key == "Id") {
                memberId = value;
                member_Id = memberId;
            }
            
            if (key == "Image") {
                $.each(value, function(key, value) {
                    if (key == "Array") {
                        $("#contact-list-container-user-information-image").attr('src', "data:image/json;base64," + value);
                    }
                });    
            }

            if (key == "Groups") {
                //group
                $.each(value, function(key, value) {
                    //friends
                    $.each(value, function(key, value) {
                        //alert(key + " " + value);
                        if (key == "Name") {
                            //alert(key + " " + value);
                            menuId = "#menu-" + value;
                            $(menuId).menu();
                            $(menuId).menu("refresh");
                            
                            $("#accordion").append("<h3 id='"+ member_Id+ "_" + value + "'>" + value + "</h3>" + "<div><ul id='menu-" + value + "'></ul></div>");
                            $("#accordion").accordion("destroy").accordion({
                                collapsible: true,
                                heightStyle: "fill"
                            });
                            
                        }
                        if (key == "Friends") {
                            $.each(value, function (key, value) {
                                //alert(key + " " + value);
                                $.each(value, function(key, value) {
                                    //alert(key + " " + value);
                                    if(key == "Id") {
                                        friendId = value;
                                    }
                                    if (key == "Name") {
                                        //alert(key + " " + value);
                                        friendName = value;
                                        
                                    }
                                    if (key == "Image") {
                                        $.each(value, function (key, value) {
                                            if (key == "Array") {
                                                imgCount++;
                                                $(menuId).append('<li><a href="#' + friendId + '">' +
                                                    '<img class="ui-icon friend-image-icon"' + ' id="id-image-' + imgCount + '" src="../images/no_avatar_28px.jpg"/>' +
                                                    '<img class="ui-icon friend-status-icon"' + ' id="id-icon-' + imgCount + '" src="../images/offline.png"/>' +
                                                    friendName + '</a></li>');
                                                
                                                $("#id-image-" + imgCount).attr('src', "data:image/json;base64," + value);
                                                
                                                $("#accordion").accordion("destroy").accordion({
                                                    collapsible: true,
                                                    heightStyle: "fill"
                                                });
                                            }
                                        });
                                    }
                                    
                                });
                            });
                            initTab(menuId);
                            
                        }
                    });
                });
            }
        });
    });

    function initTab(menu) {
        $(menu).menu();
        $(menu + " a").dblclick(function () {
            //alert($(event.target).attr('id'));
            label = $(event.target).text();
            //idContact = $(event.target).attr('id');
            idContact = $(event.target).attr('href').replace("#",""); //friend id
            var idMenuItem = $(event.target).attr('id');
            var src = $("#" + idMenuItem + " .friend-image-icon").attr('src');
            //alert(src);
            //idContact = $(event.target).attr('href');
            var dem = 0;
            for (var i = 0; i < tabArray.length; i++) {
                if(tabArray[i] == idContact) {
                    return;
                }else dem++;
            }
            if (dem == tabArray.length) {
                tabArray.push(idContact);
                addTab(idContact, src, idContact);
                event.preventDefault();
            }        
        });
        /*$(menu + " a").dblclick(function () {
            alert($(event.target).attr('id'));
            label = $(event.target).text();
            addTab();
            event.preventDefault();           
        });*/
        $(menu).menu("refresh");
    }

    function addTab(idMenuItem, src, friendId) {
        
        //var id = "tabs-" + tabCounter;

        var userImgSrc = $("#contact-list-container-user-information-image").attr("src");
        //alert(userImgSrc);

        var id = idMenuItem;
        var li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label));
        var tabContentHtml = "<div id='" + "chat-container-top-" + tabCounter + "' class='" + "chat-container-top" + "'>"
            + "<div id='" + "chat-container-messages-" + tabCounter + "' class='" + "chat-container-messages" + "'>"
            + "<dl id='list-msg-" + tabCounter + "' style='color: black'>" + "</dl>"
            + "</div>"
            + "<img id='" + "chat-container-friend-image-" + tabCounter + "' class='" + "chat-container-friend-image" + "' src='"+ src+"'/>"
            + "</div>"
            + "<div id='" + "tool-box-" + tabCounter + "' class='" + "tool-box" + "'>"
            + "<button id='" + "tool-box-send-file-" + tabCounter + "' class='" + "tool-box-send-file" + "'>" + "</button>"
            + "</div>"
            + "<div id='" + "tool-box-" + tabCounter + "1' class='" + "tool-box1" + "'>"
            + "<input type='color' name='color1' id='text-color' value=" + "'rgb(225,0,0);'/>"
            + "</div>"
            + "<div  class = 'font-text'>"
            + "<select id ='font-text'>"
            + "<option value=" + "'Arial'" + ">Arial</option>"
            + "<option value=" + "'Verdana'" + ">Verdana</option>"
            + "<option value=" + "'Impact'" + ">Impact</option>"
            + "<option value=" + "'Comic Sans MS'" + ">Comic Sans MS</option>"
            + "</select>"
            + "</div>"
            //+ "<div id = 'tool-box-share-photo-" + tabCounter + "' class = '" + "'tool-box-share-photo'>"
            + "<button id = 'share-photo-" + tabCounter + "'  class='" + "share-photo" + "'>" + "</button>"
            //+ "</div>"
            + "<div id='" + "chat-container-user-" + tabCounter + "' class='" + "chat-container-user" + "'>"
            + "<textarea id='" + "chat-container-user-textarea-" + tabCounter + "' class='" + "chat-container-user-textarea'" + " cols='" + "10' " + "rows='" + "2' " + "name='" + "textarea" + "'></textarea>"
            + "<img id='" + "chat-container-user-image-" + tabCounter + "' class='" + "chat-container-user-image' src='" + userImgSrc + "'/>"
            + "<button id='" + "chat-container-user-button-sent-" + tabCounter + "' class='" + "chat-container-user-button-sent" + "'></button>"
            + "</div>";

        tabs.find(".ui-tabs-nav").append(li);
        tabs.append("<div id='" + id + "'>" + tabContentHtml + "</div>");
        setButtonEventClick(tabCounter, friendId);
        setSharePhotoEventClick(tabCounter, friendId)
        setBoxMessEvent(tabCounter, friendId);
        tabs.tabs("refresh");
        tabCounter++;
    }
    
    //member info

    

    function setBoxMessEvent(id, friendId) {
        var textBox = $("#chat-container-user-textarea-" + id);
        textBox.bind('keypress', function (e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13) { //Enter keycode
                //Do something
                sendMessageHandler(id, friendId);             
                textBox.val('');
            }
        });
    }

    var receiver;

    function setButtonEventClick(id, friendId) {
        var button = $("#chat-container-user-button-sent-" + id);
        button.click(function () {
            sendMessageHandler(id, friendId);
            var textBox = $("#chat-container-user-textarea-" + id);
            textBox.val('');
        });
        receiver = friendId;
        
        $("#tool-box-send-file-" + id).click(function () {
            sendFile.dialog("open");
        });
       
    }

    function setSharePhotoEventClick(id, friendId) {
        $("#share-photo-" + id).click(function () {
            sharePhoto.dialog("open");
        });
    }
   
    function scrollBottom(id) {
        
        var box = $("#chat-container-messages-" + id);
        box.animate({ scrollTop: box.prop("scrollHeight") - box.height() }, 6000);
        //alert(box.attr('id'));
    }

    function sendMessageHandler(id, friendId) {
        //alert(member_Id);
        var msgContent = $("#chat-container-user-textarea-" + id).val();
        var msgBox = $("#chat-container-messages" + id);
        var dl = $("#list-msg-" + id);
        dl.append("<dt>" + "<b style='color: blue; font-size:14px'><pre>   Bé nói:</pre></b>" + "<dd id='msg' style='color: " + document.getElementById('text-color').value + "; font-family: " + document.getElementById('font-text').value + ";'>" + msgContent + "</dd>" + "</dt>");
        dl.append();
        scrollBottom(id);

        $.ajax({
            url: 'http://localhost:64395/api/Chat/Post/',
            dataType: 'json',
            data: { Message: msgContent, FriendId: friendId, UserId: member_Id },
            type: 'POST',
            success: function (data) {
                //alert(data);
            }
        });
    }
    
    (function pollStatus() {
        $.ajax({
            url: "http://localhost:64395/api/Status/Get/" + member_Id,
            success: function (data) {
                //alert(data);
                if(data != null) {
                    //alert(JSON.stringify(data));
                    
                    $.each(data, function (key, value) {
                        var friendId, groupName, status;
                        $.each(value, function (key, value) {
                            $.each(value, function (key, value) {
                                //alert(key);
                                if (key == "Id") {
                                    friendId = value;
                                }
                                if (key == "GroupName") {
                                    groupName = value;
                                }
                                if (key == "Status") {
                                    status = value;
                                }
                            });
                            if (status == "1") {
                                var icon = $("#menu-" + groupName + " .ui-menu-item a[href='#" + friendId + "'] .friend-status-icon");
                                icon.attr('src', '../images/online.png');
                            }else {
                                var icon = $("#menu-" + groupName + " .ui-menu-item a[href='#" + friendId + "'] .friend-status-icon");
                                icon.attr('src', '../images/offline.png');
                            }
                        });  
                    });
                }               
            },
            dataType: "json",
            complete: pollStatus,
            timeout: 30000
        });
    })();
    
    (function poll() {
        $.ajax({
            url: "http://localhost:64395/api/Chat/Get/" + member_Id,
            success: function (data) {
                if(data != null) {
                    //alert(JSON.stringify(data));
                    addTabReceiveMsg(data);
                }               
            },
            dataType: "json",
            complete: poll,
            timeout: 30000
        });
    })();
    (function pollPhotoShareReceive() {
        $.ajax({
            url: "http://localhost:64395/api/File/GetPhotoShared/" + member_Id,
            success: function (data) {
                if (data != null) {

                    var senderId, fileName, fileData;
                    $.each(data, function (key, value) {

                        if (key == "SenderId")
                            senderId = value;
                        if (key == "FileName")
                            fileName = value;
                        if (key == "FileData")
                            fileData = value;
                    });

                    if (senderId != null && fileName != null && fileData != null) {
                        receivePhotoShare(senderId, fileName, fileData);

                        /*$.ajax({
                            type: 'POST',
                            url: 'http://localhost:42332/WebService1.asmx/SaveFile',
                            data: { fileName: fileName, fileData: fileData },
                            dataType: 'json',
                            success: function(data) {
                                // Do something interesting here.
                                alert(data);
                                if (data == "true")
                                    alert("Success");
                            }
                        });
                        alert("You have received a file from " + senderId);*/
                    }

                }

                pollPhotoShareReceive();
            },
            dataType: "json",
            
            timeout: 500000000
        });
    })();


    (function pollFileReceive() {
        $.ajax({
            url: "http://localhost:64395/api/File/Get/" + member_Id,
            success: function (data) {
                if (data != null) {
                    //receiveFile.dialog("open"); 
                    var senderId, fileName, fileData;
                    $.each(data, function(key, value) {
                        
                        if (key == "SenderId")
                            senderId = value;
                        if (key == "FileName")
                            fileName = value;
                        if (key == "FileData")
                            fileData = value;
                    });
                    
                    if (senderId != null && fileName != null && fileData != null) {
                        receive(senderId, fileName, fileData);
                        
                        /*$.ajax({
                            type: 'POST',
                            url: 'http://localhost:42332/WebService1.asmx/SaveFile',
                            data: { fileName: fileName, fileData: fileData },
                            dataType: 'json',
                            success: function(data) {
                                // Do something interesting here.
                                alert(data);
                                if (data == "true")
                                    alert("Success");
                            }
                        });
                        alert("You have received a file from " + senderId);*/
                    }

                }

                pollFileReceive();
            },
            dataType: "json",
            //complete: pollFileReceive,
            timeout: 500000000
        });
    })();

   
    //tao tab khi co friend chat qua
    function addTabReceiveMsg(data) {     
        $.each(data, function (key, value) {
                  
            $.each(value, function (key, value) {
                var friendId, msg, dem, src;
                dem = 0;
                src = "";
                $.each(value, function (key, value) {
                    if (key == "Message")
                        msg = value;
                    if (key == "FriendId")
                        friendId = value;
                });
                
                for (var i = 0; i < tabArray.length; i++) {
                    if (tabArray[i] == friendId) {
                        //them message vao box
                        //alert("tab da co ne");
                        var dl = $("#" + friendId + " .chat-container-top .chat-container-messages dl");
                        //alert(msg);
                        dl.append("<dt>" + "<b style='color: blue; font-size:14px'><pre>   " + friendId + ":</pre></b>" + "<dd id='msg' style='color: " + document.getElementById('text-color').value + "; font-family: " + document.getElementById('font-text').value + ";'>" + msg + "</dd>" + "</dt>");
                        dl.append();
                        var box = $("#" + friendId + " .chat-container-top .chat-container-messages");
                        box.animate({ scrollTop: box.prop("scrollHeight") - box.height() }, 6000);
                        //alert(dl.attr('id'));
                        break;
                    } else dem++;
                }
                if (dem == tabArray.length) {
                    tabArray.push(friendId);
                    addTabHasMsg(friendId, src, friendId, msg);
                    
                    event.preventDefault();
                }
  
            });
            
        });
        
        function addTabHasMsg(idMenuItem, src, friendId, message) {

            //var id = "tabs-" + tabCounter;
            var userImgSrc = $("#contact-list-container-user-information-image").attr("src");
            //alert(userImgSrc);

            var id = idMenuItem;
            var li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, id));
            var tabContentHtml = "<div id='" + "chat-container-top-" + tabCounter + "' class='" + "chat-container-top" + "'>"
                + "<div id='" + "chat-container-messages-" + tabCounter + "' class='" + "chat-container-messages" + "'>"
                + "<dl id='list-msg-" + tabCounter + "' style='color: black'>" + "</dl>"
                + "</div>"
                + "<img id='" + "chat-container-friend-image-" + tabCounter + "' class='" + "chat-container-friend-image" + "' src='" + src + "'/>"
                + "</div>"
                + "<div id='" + "tool-box-" + tabCounter + "' class='" + "tool-box" + "'></div>"
                 + "<button id='" + "tool-box-send-file-" + tabCounter + "' class='" + "tool-box-send-file" + "'>" + "</button>"
                 + "</div>"
                + "<div id='" + "tool-box-" + tabCounter + "1' class='" + "tool-box1" + "'>"
                + "<input type='color' name='color1' id='text-color' value=" + "'rgb(225,0,0);'/>"
                + "</div>"
                + "<div class = 'font-text'>"
                + "<select id= 'font-text'>"
                + "<option value=" + "'Arial'" + ">Arial</option>"
                + "<option value=" + "'Verdana'" + ">Verdana</option>"
                + "<option value=" + "'Impact'" + ">Impact</option>"
                + "<option value=" + "'Comic Sans MS'" + ">Comic Sans MS</option>"
                + "</select>"
                + "</div>"
                //+ "<div id = 'tool-box-share-photo-" + tabCounter + "' class = '" + "'tool-box-share-photo'>"
                + "<button id = 'share-photo-" + tabCounter + "'  class='" + "share-photo" + "'>" + "</button>"
                //+ "</div>"
                + "<div id='" + "chat-container-user-" + tabCounter + "' class='" + "chat-container-user" + "'>"
                + "<textarea id='" + "chat-container-user-textarea-" + tabCounter + "' class='" + "chat-container-user-textarea'" + " cols='" + "10' " + "rows='" + "2' " + "name='" + "textarea" + "'></textarea>"
                + "<img id='" + "chat-container-user-image-" + tabCounter + "' class='" + "chat-container-user-image' src='" + userImgSrc + "'/>"
                + "<button id='" + "chat-container-user-button-sent-" + tabCounter + "' class='" + "chat-container-user-button-sent" + "'></button>"
                + "</div>";

            tabs.find(".ui-tabs-nav").append(li);
            tabs.append("<div id='" + id + "'>" + tabContentHtml + "</div>");          
            setButtonEventClick(tabCounter, friendId);
            setSharePhotoEventClick(tabCounter, friendId);
            setBoxMessEvent(tabCounter, friendId);
            tabs.tabs("refresh");            
            setSendMessage(tabCounter, friendId, message);
            tabCounter++;
        }
    }
    
    function setSendMessage(id, friendId, message) {
        var dl = $("#list-msg-" + id);
        //alert("#list-msg-" + id);
        dl.append("<dt>" + "<b style='color: blue; font-size:14px'><pre>   " + friendId + ":</pre></b>" + "<dd id='msg' style='color: " + document.getElementById('text-color').value + ";'>" + message + "</dd>" + "</dt>");
        dl.append();
        var box = $("#" + friendId + " .chat-container-top .chat-container-messages");
        box.animate({ scrollTop: box.prop("scrollHeight") - box.height() }, 6000);
    }


    //remove tab
    $("#tabs span.ui-icon-close").live("click", function () {
        var panelId = $(this).closest("li").remove().attr("aria-controls");
        $("#" + panelId).remove();
        //alert(panelId);
        var buttonId = panelId.charAt(panelId.length - 1);
        $("#chat-container-user-button-sent-" + buttonId).off("click");
        tabCounter--;
        tabArray = jQuery.grep(tabArray, function(value) {
            return value != panelId;
        });
        tabs.tabs("refresh");
    });
    
    var addFriendDialog = $("#add-friend-dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            Add: function () {
                addFriendHandler();
                $(this).dialog("close");
                $("#friend-id-add").val("").removeClass("ui-state-error");
                $("#group-option").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#friend-id-add").val("").removeClass("ui-state-error");
                $("#group-option").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#friend-id-add").val("").removeClass("ui-state-error");
            $("#group-option").val("").removeClass("ui-state-error");
        }
    });

    function addFriendHandler() {
        var friendId = $("#friend-id-add").val();
        //alert(friendId);
        var groupName = $("#group-option").val();
        //alert(groupName);
        /*$.ajax({
            type: "POST",
            url: "http://localhost:64395/api/Account",
            data: $.parseJSON('{' + '"UserName":"' + username + '","Password":"' + password + '"}'),
            dataType: 'json',
            //data: $.parseJSON("UserName=" + username + "&Password=" + password),
            success: function (answer) {
                $("#login-dialog").hide();
                alert("success");
            }
        });*/

        $.post("http://localhost:64395/api/Friend/Post/", { Id: friendId, Name: friendId, Image: null, MemberId: member_Id, GroupName: groupName, State: "false" }, function (data) {
            //alert(JSON.stringify(data));
            if (data != null) {
                imgCount++;
                var id, name, image = null;
                $.each(data, function(key, value) {

                    if (key == "Id")
                        id = value;
                    if (key == "Name")
                        name = value;
                    if (key == "Image") {
                        $.each(value, function(key, value) {
                            if (key == "Array")
                                image = value;
                        });
                    }
                });
                $("#menu-" + groupName).append('<li><a href="#' + friendId + '">' +
                    '<img class="ui-icon friend-image-icon"' + ' id="id-image-' + imgCount + '" src="../images/no_avatar_28px.jpg"/>' +
                    '<img class="ui-icon friend-status-icon"' + ' id="id-icon-' + imgCount + '" src="../images/offline.png"/>' +
                    name + '</a></li>');
                $("#id-image-" + imgCount).attr('src', "data:image/json;base64," + image);
                $("#menu-" + groupName).addClass("ui-menu-icons");
                $("#menu-" + groupName).menu("refresh");
                initTab("#menu-" + groupName);
            }else {
                alert("fail");
            }
        });


    }

    var deleteFriendDialog = $("#delete-friend-dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            Delete: function () {
                deleteFriendHandler();
                $(this).dialog("close");
                $("#friend-id-delete").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#friend-id-delete").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#friend-id-delete").val("").removeClass("ui-state-error");
        }
    });

    function deleteFriendHandler() {
        var friendId = $("#friend-id-delete").val();
        //alert(friendId);
        $.ajax({
            type: "DELETE",
            url: "http://localhost:64395/api/Friend/Delete/" + member_Id + 'id=' + friendId,
            dataType: 'json',
            //data: $.parseJSON("UserName=" + username + "&Password=" + password),
            success: function (answer) {
                $("#delete-friend-dialog").hide();
                //alert("success");
                if (answer != null) {
                    var a = $("#menu-" + answer + " .ui-menu-item a[href='#" + friendId + "']");
                    //alert(a.attr('id'));
                    a.remove();
                    $("#menu-" + answer).menu("refresh");
                } else {
                    alert("error");
                }
            }
        });
    }

    var addGroupDialog = $("#add-group-dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            Add: function () {
                addGroupHandler();
                $(this).dialog("close");
                $("#group-id-add").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#group-id-add").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#group-id-add").val("").removeClass("ui-state-error");
        }
    });

    function addGroupHandler() {
        var groupname = $("#group-id-add").val();
        //alert(groupname);
        var memberId = member_Id;
        //alert(memberId);
        /*$.ajax({
            type: "POST",
            url: "http://localhost:64395/api/Account",
            data: $.parseJSON('{' + '"UserName":"' + username + '","Password":"' + password + '"}'),
            dataType: 'json',
            //data: $.parseJSON("UserName=" + username + "&Password=" + password),
            success: function (answer) {
                $("#login-dialog").hide();
                alert("success");
            }
        });*/

        $.post("http://localhost:64395/api/Group/Post/", { GroupId: "0", UserName: memberId, Name: groupname, Friends: null }, function (data) {
            //alert(JSON.stringify(data));
            if (data != null) {
                $("#accordion").append("<h3 id='" + memberId + "_" + groupname + "'>" + groupname + "</h3>" + "<div><ul id='menu-" + groupname + "'></ul><div>");
                $("#accordion").accordion("destroy").accordion({
                    collapsible: true,
                    heightStyle: "fill"
                });
                var menuId = "#menu-" + groupname;
                $(menuId).menu();
                $(menuId).menu("refresh");
                alert("success");
            }else {
                alert("fail");
            }
        });
    }

    var deleteGroupDialog = $("#delete-group-dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            Delete: function () {
                deleteGroupHandler();
                $(this).dialog("close");
                $("#group-id-delete").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#group-id-delete").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#group-id-delete").val("").removeClass("ui-state-error");
        }
    });

    function deleteGroupHandler() {
        var groupname = $("#group-id-delete").val();
        var groupId = member_Id + "_" + groupname;
        //alert(groupname);
        var memberId = member_Id;
        //alert(memberId);
        $.ajax({
            type: "DELETE",
            url: "http://localhost:64395/api/Group/Delete/" + groupId,
            dataType: 'json',
            //data: $.parseJSON("UserName=" + username + "&Password=" + password),
            success: function (answer) {
                $("#delete-group-dialog").hide();
                alert("success");
                var menuId = "#menu-" + groupname;
                var parent = $(menuId).parent();
                $(menuId).remove();
                $("#" + member_Id + "_" + groupname).remove();
                parent.remove();
                $("#accordion").accordion("destroy").accordion({
                    collapsible: true,
                    heightStyle: "fill"
                });
            }
        });
    }

    var updateMemberDialog = $("#update-member-dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            Update: function () {
                editMemberHandler();
                $(this).dialog("close");
                $("#update-name").val("").removeClass("ui-state-error");
                $("#update-password").val("").removeClass("ui-state-error");
                $("#update-password-confirm").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#update-name").val("").removeClass("ui-state-error");
                $("#update-password").val("").removeClass("ui-state-error");
                $("#update-password-confirm").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#update-name").val("").removeClass("ui-state-error");
            $("#update-password").val("").removeClass("ui-state-error");
            $("#update-password-confirm").val("").removeClass("ui-state-error");
        }
    });

    function editMemberHandler() {
        var membername = $("#update-name").val();
        var newPassword = $("#update-password").val();
        var newPasswordConfirm = $("#update-password-confirm").val();

        if (newPassword == newPasswordConfirm) {
            $.ajax({
                url: 'http://localhost:64395/api/Member/Post/' + member_Id,
                dataType: 'json',
                data: { Id: member_Id, Name: membername, Password: newPassword },
                type: 'POST',
                success: function(data) {
                    //alert(data);
                    $("#" + member_Id).remove();
                    $("#contact-list-container-user-information-name").append("<b id='" + member_Id + "'>" + membername + "</b>");
                }
            });
        }else {
            alert("Password retype and password different");
        }
    }

    var uploadImage = $("#postAvatar").dialog({
        autoOpen: false,
        modal: true,
        width: 400,
        buttons: {
            Update: function () {
                uploadImageHandle();
                $(this).dialog("close");
                $("#file").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#file").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#file").val("").removeClass("ui-state-error");
        }
    });

    function uploadImageHandle() {
        var newImage = $("#file")[0].files[0];
        var formData = new FormData();
        formData.append("file", newImage);

        //alert(formData);

        $.ajax({
            url: 'http://localhost:64395/api/' + 'Image/Post?id=' + member_Id,
            data: formData, //{ id: member_Id, file: formData },
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function (data) {
                $("#contact-list-container-user-information-image").attr('src', "data:image/json;base64," + data);
            }
        });
    }
    

    var sendFile = $("#sendFile").dialog({
        autoOpen: false,
        modal: true,
        width: 400,
        buttons: {
            Send: function () {
                sendFileHandle();
                $(this).dialog("close");
                $("#filesend").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#filesend").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#filesend").val("").removeClass("ui-state-error");
        }
    });
    

    function sendFileHandle() {
        var newFile = $("#filesend")[0].files[0];
        
        var fileName = newFile.name;
        var formData = new FormData();
        formData.append("filesend", newFile);

        //alert(formData);

        $.ajax({
            url: 'http://localhost:64395/api/' + 'File/Post?senderid=' + member_Id + "&filename=" + fileName + "&receiverid=" + receiver,
            data: formData, //{ id: member_Id, file: formData },
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function (data) {
                alert("Success!!!");
            }
        });
    }

    var sharePhoto = $("#sharePhoto").dialog({
        autoOpen: false,
        modal: true,
        width: 400,
        buttons: {
            OK: function () {
                var newFile = $("#file1")[0].files[0];
                alert(newFile.name);
                $("#photoShare").attr('src', newFile);
                alert(newFile.name);
                sharePhotoHandle;
                $(this).dialog("close");
                $("#sharePhoto").val("").removeClass("ui-state-error");
            },
            Cancel: function () {
                $(this).dialog("close");
                $("#sharePhoto").val("").removeClass("ui-state-error");
            }
        },
        close: function () {
            $("#sharePhoto").val("").removeClass("ui-state-error");
        }
    });

    function sharePhotoHandle() 
    {
        
        var newPhoto = $("#file1")[0].files[0];
        var fileName = newPhoto.name;
        alert(fileName);
        var formData = new FormData();
        formData.append("file1", newPhoto);
        
        $.ajax({
            url: 'http://localhost:64395/api/' + 'Photo/Share?senderid=' + member_Id + "&filename=" + fileName + "&receiverid=" + receiver,
            data: formData, //{ id: member_Id, file: formData },
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function (data) {
                sharePhoto.dialog("open");
                $("#photoShare").attr('src', "data:image/json;base64," + data);
                
            },
            fail: function(data)
            {
                alert("Fail");
            },
            
        });
    }

    var sharePhoto = $("#Form-share-photo").dialog({
        autoOpen: false,
        modal: true,
        width: 650,
        buttons:
            {
                OK: function () {
                   sharePhotoHandle();
                },
                Cancel: function () {
                    $(this).dialog("close");
                    $("#Form-share-photo").val("").removeClass("ui-state-error");
                },
                close: function () {
                    $(this).dialog("close");
                    $("#Form-share-photo").val("").removeClass("ui-state-error");
                }
            }
    
    });

    function receive(senderId, fileName, fileData) {
        var receiveFile = $("#receive-file").dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            buttons: {
                Receive: function () {
                    //sendFileHandle();
                    $.ajax({
                        type: 'POST',
                        url: 'http://localhost:42332/WebService1.asmx/SaveFile',
                        data: { fileName: fileName, fileData: fileData },
                        dataType: 'json',
                        success: function (data) {
                            // Do something interesting here.
                            alert(data);
                            if (data == "true")
                                alert("Success");
                        }
                    });
                    alert("You have received a file from " + senderId);

                    $(this).dialog("close");
                    $("#filereceive").val("").removeClass("ui-state-error");
                },
                Cancel: function () {
                    $(this).dialog("close");
                    $("#filereceive").val("").removeClass("ui-state-error");
                }
            },
            close: function () {
                $("#filereceive").val("").removeClass("ui-state-error");
            }
        });
        receiveFile.dialog("open");
    }

    function receivePhotoShare(senderId, fileName, fileData) {
        var photoShare = $("#accept-share-photo").dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            buttons: {
                Accept: function () {
                    $.ajax({
                        type: 'POST',
                        url: 'http://localhost:42332/WebService1.asmx/GetPhotoShared',
                        data: { fileName: fileName, fileData: fileData },
                        dataType: 'json',
                        success: function (data) {
                            $(this).dialog("close");
                            sharePhoto.dialog("open");
                            $("#photoShare").attr('src', "data:image/json;base64," + data);
                        }
                    });                                
                                    
                },
                Cancel: function () {
                    $(this).dialog("close");
                    $("#accept-share-photo").val("").removeClass("ui-state-error");
                }
            },
            close: function () {
                $(this).dialog("close");
                $("#accept-share-photo").val("").removeClass("ui-state-error");
            }
        });
       
    }


    $("#add-friend-button").click(function () {
        addFriendDialog.dialog("open");
    });

    $("#delete-friend-button").click(function () {
        deleteFriendDialog.dialog("open");
    });

    $("#add-group-button").click(function () {
        addGroupDialog.dialog("open");
    });

    $("#delete-group-button").click(function () {
        deleteGroupDialog.dialog("open");
    });

    $("#edit-user-img-button").click(function () {
        uploadImage.dialog("open");
    });

    $("#edit-user-info-button").click(function () {
        updateMemberDialog.dialog("open");
    });

    $("#user-logout-button").click(function () {
        $.ajax({
            url: 'http://localhost:64395/api/Status/Post/' + member_Id,
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                //alert(data);
                //alert(member_Id);
                $.cookie('username', null);
                jQuery(document).empty();
                window.location.href = "/index.html";
            }
        });
        
    });
    

    

    //$.ajax({
    //    url:"http://localhost:64395/api/group/4",
    //    type:"DELETE",
    //    success: function (data) {
    //        alert("dc ui");
    //    },
    //    error: function (jqXHR, textStatus, errorThrown) {
    //        alert("Error");
    //    }
    //});
});

//0912434
$(function () {
    $("#btnVideo").click(function () {
        window.open("VideoChat.aspx", 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=435');
    });
    $("#btnVoice").click(function () {
        window.open("VoiceChat.aspx", 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=435');
    });
});